package com.itheima.restkeeper.handler.wechat.operators.baisc;

import com.alibaba.fastjson.JSONObject;
import com.itheima.restkeeper.handler.wechat.client.Config;
import com.itheima.restkeeper.handler.wechat.client.WechatPayHttpClient;
import com.itheima.restkeeper.handler.wechat.response.QueryResponse;
import com.itheima.restkeeper.handler.wechat.response.RefundResponse;
import com.itheima.restkeeper.utils.ExceptionsUtil;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.log4j.Log4j2;

import java.io.IOException;
import java.io.Serializable;
import java.net.URISyntaxException;

/**
 * @ClassName BasicQuery.java
 * @Description TODO
 */
@EqualsAndHashCode(callSuper = true)
@Log4j2
@Data
public class BasicQuery extends SystemParams {

    public BasicQuery(Config config) {
        super(config);
    }

    /***
     * @description 统一收单线下交易查询【native和jsapi通用】
     * @param outTradeNo 发起支付传递的交易单号
     * @return
     */
    public QueryResponse query(String outTradeNo) {
        //请求地址
        String uri = "/v3/pay/transactions/out-trade-no";
        WechatPayHttpClient httpClient = WechatPayHttpClient.builder()
                .mchId(mchId)
                .mchSerialNo(mchSerialNo)
                .apiV3Key(apiV3Key)
                .privateKey(privateKey)
                .domain(domain + uri)
                .build();
        String body = null;
        try {
            //uri参数对象
            String uriParams = "/" + outTradeNo + "?mchid=" + mchId;
            body = httpClient.doGet(uriParams);
        } catch (IOException | URISyntaxException e) {
            log.error("微信支付：query，发生异常：{}", ExceptionsUtil.getStackTraceAsString(e));
        }
        QueryResponse queryResponse = JSONObject.parseObject(body, QueryResponse.class);
        queryResponse.setCode("200");
        return queryResponse;
    }

    /***
     * @description 统一收单交易退款接口查询
     * @param outRefundNo 商户系统内部的退款单号
     * @return
     */
    public RefundResponse queryRefund(String outRefundNo) {
        //请求地址
        String uri = "/v3/refund/domestic/refunds";
        WechatPayHttpClient httpClient = WechatPayHttpClient.builder()
                .mchId(mchId)
                .mchSerialNo(mchSerialNo)
                .apiV3Key(apiV3Key)
                .privateKey(privateKey)
                .domain(domain + uri)
                .build();
        String body = null;
        try {
            String uriParams = "/" + outRefundNo;
            body = httpClient.doGet(uriParams);
        } catch (IOException | URISyntaxException e) {
            log.error("微信支付：queryRefund，发生异常：{}", ExceptionsUtil.getStackTraceAsString(e));
        }
        RefundResponse refundResponse = JSONObject.parseObject(body, RefundResponse.class);
        refundResponse.setCode("200");
        return refundResponse;
    }

}
